package com.ztjava.common.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.ztjava.common.model.tree.TreeInfo;
import com.ztjava.common.model.tree.TreeItem;
import com.ztjava.core.Constant;
import com.ztjava.core.base.BaseService;
import com.ztjava.core.client.Client;

public class TreeService extends BaseService{
	public Page<TreeInfo> infoPage(Client client,Map<String,String[]> paramMap){
		String[][] param = new String[][]{
				new String[]{"name",like,"name"}
				,new String[]{"code",like,"code"}
		};
		Page<TreeInfo> pd = TreeInfo.dao.paginate(
				getParaToInt(paramMap, client.getPageNumber(), 1), 
				getParaToInt(paramMap,client.getPageSize(),20),
				"select *","from "+TreeInfo.tablename+" where 1=1 " 				
				+ whereSql(paramMap,param)
				+ orderby(client, paramMap),whereParam(paramMap, param));
		return pd;
	}
	public void loadInfoCache(){
		List<TreeInfo> infoList = TreeInfo.dao.find("select * from "+TreeInfo.tablename+" order by id asc");
		List<TreeItem> itemList = TreeItem.dao.find("select * from "+TreeItem.tablename+" order by sort asc,id asc");
		Cache cache = Redis.use();
		for(int i=0,il = infoList.size();i<il;i++){
			List<JSONObject> info = itemToTree(infoList.get(i).getInt("id"), 0, itemList);
			cache.hset(Constant.R_TREE, infoList.get(i).getStr("code"), info);
			System.out.println("树形菜单："+infoList.get(i).getStr("code"));
		}
	}
	public void loadInfoCache(Integer id){
		TreeInfo treeInfo = TreeInfo.dao.findById(id);
		List<TreeItem> itemList = TreeItem.dao.find("select * from "+TreeItem.tablename+" order by sort asc,id asc");
		Cache cache = Redis.use();
		List<JSONObject> info = itemToTree(treeInfo.getInt("id"), 0, itemList);
		cache.hset(Constant.R_TREE, treeInfo.getStr("code"), info);
		System.out.println("树形菜单："+treeInfo.getStr("code"));
	}
	
	public List<JSONObject> itemToTree(Integer info_id,Integer parent_id,List<TreeItem> itemList){
		List<JSONObject> info = new ArrayList<JSONObject>();
		TreeItem item = null;
		for(int i=0,il = itemList.size();i<il;i++){
			item = itemList.get(i);
			if(!item.getInt("info_id").equals(info_id)){
				continue;
			}
			if(!item.getInt("parent_id").equals(parent_id)){
				continue;
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("id", item.getInt("id"));
			jsonObject.put("name", item.getStr("name"));
			jsonObject.put("image", item.getStr("image"));
			jsonObject.put("url", item.getStr("url"));
			jsonObject.put("icon", item.getStr("icon"));
			jsonObject.put("children", itemToTree(info_id, item.getInt("id"), itemList));
			info.add(jsonObject);
		}
		return info;
	}
}
